package v1

import (
	"bc/service"
	"bc/util"
	"bc/util/library/zstack"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strconv"
)

type ins_off struct {

}
func (t *ins_off) First(c *gin.Context){

	w := make(map[string]interface{})
	w["io_id"] = c.Param("io_id")

	data := service.InsOffer.First(w)

	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":data,
	})

}
func (t *ins_off) Find(c *gin.Context){
	w := make(map[string]interface{})
	page := c.DefaultQuery("page","1")
	npage,_ := strconv.Atoi(page)
	pageSize := c.DefaultQuery("pageSize",strconv.FormatInt(util.Config.App.PageSize,10))
	npageSize,_ := strconv.Atoi(pageSize)

	data,total := service.InsOffer.Find(w,npage,npageSize)
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":data,
		"total":total,
	})

}
func (t *ins_off) Create(c *gin.Context){

	d := make(map[string]interface{})

	d["name"] = c.PostForm("name")
	//d["description"] = c.PostForm("desc")

	if v,ok := c.GetPostForm("cpu_num");ok{
		cpu_num,_ := strconv.ParseInt(v,10,64)
		d["cpu_num"] = cpu_num
	}

	if v,ok := c.GetPostForm("cpu_speed");ok{
		cpu_speed,_ := strconv.ParseInt(v,10,64)
		d["cpu_speed"] = cpu_speed
	}

	if v,ok := c.GetPostForm("memory_size");ok{
		memory_size,_ := strconv.ParseInt(v,10,64)
		d["memory_size"] = memory_size
	}

	if v,ok := c.GetPostForm("allocator_strategy");ok{
		d["allocator_strategy"] = v
	}

	if v,ok := c.GetPostForm("sort_key");ok{
		sort_key,_ := strconv.ParseInt(v,10,64)
		d["sort_key"] = sort_key
	}
	if v,ok := c.GetPostForm("type");ok{
		d["type"] = v
	}
	if v,ok := c.GetPostForm("resource_uuid");ok{
		d["resource_uuid"] = v
	}
	//d["system_tags"] = c.PostForm("system_tags")
	//d["user_tags"] = c.PostForm("user_tags")
	if v,ok := c.GetPostForm("state");ok{
		d["state"] = v
	}else{
		d["state"] = "Enabled"
	}

	ins := map[string]interface{}{
		"name":d["name"].(string),
		"cpu_num" : d["cpu_num"].(int64),
		"memory_size" : d["memory_size"].(int64) * 1024 * 1024 * 1024,
		"sort_key" : d["sort_key"],
		"type" : d["type"],
	}
	oauth , err:= zstack.Account.LogInByAccount(map[string]string{
		"username":util.Config.Zstack.UserName,
		"password":util.Config.Zstack.Password,
	})
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}
	inven := oauth["inventory"].(map[string]interface{})
	uuid := inven["uuid"].(string)
	data ,err := zstack.InsOffer.Create(ins,uuid)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"添加规格成功",
		"data":data,
	})
}
func (t *ins_off) CreateCallBack(c *gin.Context){

	m := make(map[string]interface{})

	b,e := ioutil.ReadAll(c.Request.Body)
	if e != nil{
		panic(e)
	}
	/*
	f,errr := os.OpenFile("./_runtime/aa.txt",os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if errr != nil{
		fmt.Println(errr)
	}
	defer f.Close()
	_,er := f.Write(b)
	if er != nil{
		panic(er)
	}*/

	err := json.Unmarshal(b,&m)
	if err != nil{
		return
	}

	nm := m["inventory"].(map[string]interface{})
	nm["uid"] = c.GetInt("uid")

	defer c.Request.Body.Close()
	service.InsOffer.Create(nm)
	return
}
func (t *ins_off) Delete(c *gin.Context){

	w := make(map[string]interface{})
	w["io_id"] = c.Param("io_id")
	w["resource_uuid"] = c.Param("uuid")

	oauth,err := zstack.Account.LogInByAccount(map[string]string{
		"username":util.Config.Zstack.UserName,
		"password":util.Config.Zstack.Password,
	})
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}

	inven := oauth["inventory"].(map[string]interface{})
	uuid := inven["uuid"].(string)
	str,err := zstack.InsOffer.Delete(w["resource_uuid"].(string),uuid)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"删除成功",
		"data":str,
	})

}
func (t *ins_off) DelCallBack(c *gin.Context){

	b := c.Query("uuid")
/*
	f,errr := os.OpenFile("./_runtime/aa.txt",os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if errr != nil{
		fmt.Println(errr)
	}
	defer f.Close()
	_,er := f.Write([]byte(b))
	if er != nil{
		panic(er)
	}*/
	if b != ""{
		w := map[string]interface{}{
			"resource_uuid":b,
		}
		bool := service.InsOffer.Delete(w)
		if bool == true{
			c.JSON(200,gin.H{
				"code":200,
				"msg":"成功",
			})
			return
		}
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
	}
}
func (t *ins_off) Update(c *gin.Context){
/*
	w := map[string]interface{}{
		"io_id":c.Param("io_id"),
	}*/
	d := make(map[string]interface{})
	if c.PostForm("name") != ""{
		d["name"] = c.PostForm("name")
	}

	//d["description"] = c.PostForm("desc")

	cpu_num,b := c.GetPostForm("cpu_num")
	if b{
		cpu_num_l,_ := strconv.ParseInt(cpu_num,10,64)
		d["cpu_num"] =  cpu_num_l
	}

	cpu_speed,b := c.GetPostForm("cpu_speed")
	if b{
		cpu_speed_l,_ := strconv.ParseInt(cpu_speed,10,64)
		d["cpu_speed"] = cpu_speed_l
	}

	memory_size , b := c.GetPostForm("memory_size")
	if b{
		memory_size_l ,_ := strconv.ParseInt(memory_size,10,64)
		d["memory_size"] = memory_size_l
	}

	allocator_strategy , b := c.GetPostForm("allocator_strategy")
	if b{
		d["allocator_strategy"] = allocator_strategy
	}

	sort_key ,b := c.GetPostForm("sort_key")
	if b{
		sort_key_l,_ :=strconv.ParseInt(sort_key,10,64)
		d["sort_key"] = sort_key_l
	}
	type_str,b := c.GetPostForm("type")
	if b{
		d["type"] = type_str
	}
	uuid ,b := c.GetPostForm("resource_uuid")
	if b {
		d["resource_uuid"] = uuid
	}


	//d["system_tags"] = c.PostForm("system_tags")
	//d["user_tags"] = c.PostForm("user_tags")
	state ,b := c.GetPostForm("state")
	if b {
		d["state"] = state
	}
	oauth,err := zstack.Account.LogInByAccount(map[string]string{
		"username":util.Config.Zstack.UserName,
		"password":util.Config.Zstack.Password,
	})
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}
	inven := oauth["inventory"].(map[string]interface{})
	oauth_uuid := inven["uuid"].(string)

	updateJson := make(map[string]interface{})
	updateJson["updateInstanceOffering"] = d

	jsond,err := json.Marshal(updateJson)
	if err != nil{
		panic(err)
	}
	io_uuid := c.Param("uuid")
	str,err := zstack.InsOffer.Update(string(jsond),io_uuid,oauth_uuid)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"成功",
		"data":str,
	})

}
func (t *ins_off)UpdateCallBack(c *gin.Context){

	b ,_:= ioutil.ReadAll(c.Request.Body)
	/*
	f,errr := os.OpenFile("./_runtime/aa.txt",os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if errr != nil{
		fmt.Println(errr)
	}

	defer f.Close()
	_,er := f.Write([]byte(b))
	if er != nil{
		panic(er)
	}*/
	m := make(map[string]interface{})
	err := json.Unmarshal(b,&m)
	if err != nil{
		panic(err)
	}
	if _,ok := m["error"];ok{
		return
	}

	inventory := make(map[string]interface{})
	inventory = m["inventory"].(map[string]interface{})

	w := map[string]interface{}{
		"resource_uuid" : inventory["uuid"],
	}

	setd := make(map[string]interface{})
	setd["name"] = inventory["name"]
	setd["cpu_num"] = inventory["cpuNum"]
	setd["cpu_speed"] = inventory["cpuSpeed"]
	setd["memory_size"] = inventory["memorySize"]
	setd["type"] = inventory["type"]
	setd["allocator_strategy"] = inventory["allocatorStrategy"]
	setd["sort_key"] = inventory["sortKey"]
	setd["state"] = inventory["state"]

	bool := service.InsOffer.Update(w,setd)
	if bool == true{
		c.JSON(200,gin.H{
			"code":200,
			"msg":"操作成功",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":500,
		"msg":"error",
	})
}
/**
	修改计算规格状态
 */
func (t *ins_off)ChangeInstanceOfferingState(c *gin.Context){

	uuid := c.Param("uuid")
	if uuid == ""{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"uuid参数必填",
		})
		return
	}

	reqData := make(map[string]map[string]interface{})
	reqData["changeInstanceOfferingState"] = make(map[string]interface{})

	if v,ok := c.GetPostForm("state");ok{
		state := []string{"enable","disable"}
		isExist := false
		for _,vs := range state{
			if vs == v{
				isExist = true
				break
			}
		}
		if isExist == false{
			c.JSON(200,gin.H{
				"code":500,
				"msg":"error",
				"data":"启用状态值只能为[enable,disable]",
			})
			return
		}

		reqData["changeInstanceOfferingState"]["stateEvent"] = v
	}else{
		reqData["changeInstanceOfferingState"]["stateEvent"] = "enable"
	}

	byte,err := json.Marshal(reqData)
	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"数据有误，请重试",
		})
		return
	}

	str,err := zstack.InsOffer.ChangeInstanceOfferingState(uuid,string(byte))
	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"错误，请重试",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":str,
	})

}
func (t *ins_off)ChangeInstanceOfferingStateCallBack(c *gin.Context){

	uuid := c.Query("uuid")
	if uuid == ""{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
		return
	}
	byte,err := ioutil.ReadAll(c.Request.Body)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
		return
	}
	defer c.Request.Body.Close()

	data := map[string]interface{}{}
	data["error"] = make(map[string]interface{})

	err = json.Unmarshal(byte,&data)

	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
		return
	}

	if len(data["error"].(map[string]interface{})) > 0{
		errdata := make(map[string]interface{})
		errdata = data["error"].(map[string]interface{})
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":errdata["details"],
		})
		fmt.Println(errdata["details"])
		return
	}

	inv := make(map[string]interface{})
	inv = data["inventory"].(map[string]interface{})

	bool := service.InsOffer.Update(map[string]interface{}{"resource_uuid":uuid},map[string]interface{}{"state":inv["state"]})
	if bool {
		c.JSON(200,gin.H{
			"code":200,
			"msg":"操作成功",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":500,
		"msg":"error",
	})
}
var InsOffer = &ins_off{}